package com.apex.lottery.service.strategy.execution;

import cn.hutool.core.date.DateUtil;
import com.apex.lottery.common.utils.JacksonUtil;
import com.apex.lottery.common.utils.SMSUtil;
import com.apex.lottery.dao.dataobject.WinningRecordDO;
import com.apex.lottery.service.enums.ActivityPrizeTiersEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @ClassName SendMessageStrategy
 * @Description
 * @Author ZJX
 * @Date 2025/4/23 19:46
 * @Version 1.0
 **/

@Slf4j
@Component
public class SendMessageStrategy implements TaskExecutionStrategy{
    @Autowired
    private SMSUtil smsUtil;

    @Qualifier("asyncServiceExecutor")
    private final ThreadPoolTaskExecutor threadPoolTaskExecutor;

    public SendMessageStrategy(@Qualifier("asyncServiceExecutor") ThreadPoolTaskExecutor threadPoolTaskExecutor) {
        this.threadPoolTaskExecutor = threadPoolTaskExecutor;
    }

    @Override
    public void execute(List<WinningRecordDO> winningRecordDOList) {
        threadPoolTaskExecutor.execute(() -> sendMessage(winningRecordDOList));
    }

    private void sendMessage(List<WinningRecordDO> winningRecordDOList) {
        // 发送消息的逻辑
        if (CollectionUtils.isEmpty(winningRecordDOList)) {
            log.info("中奖列表为空，不用发短信！");
            return;
        }

        winningRecordDOList
                .forEach(winningRecordDO -> {
                    Map<String, String> map = new HashMap<>();
                    map.put("name", winningRecordDO.getWinnerName());
                    map.put("activityName", winningRecordDO.getActivityName());
                    map.put("prizeTiers", Objects.requireNonNull(ActivityPrizeTiersEnum.forName(winningRecordDO.getPrizeTier())).getMessage());
                    map.put("prizeName", winningRecordDO.getPrizeName());
                    map.put("winningTime", DateUtil.formatTime(winningRecordDO.getWinningTime()));

                    // 发送短信
                    smsUtil.sendMessage("SMS_465985911",
                            winningRecordDO.getWinnerPhoneNumber().getValue(),
                            JacksonUtil.writeValueAsString(map));
                });
    }
}
